const app = getApp();
const recorderManager = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext();
var upload = require('../../utils/upload');
var times; //录音倒计时
Page({
  data: {
    disabled:false,
    sheet:false,
    actions: [
      { name: '一般','level': 0},
      { name: '中等','level': 1},
      { name: '危险','level': 2},
      { name: '超急','level':3,color: '#FF0000' }
    ],
    level:0,
    urgent:'一般',
    product_id: 0,
    product_code:'',
    address: [],
    address_isnull: 0,
    order_product_id:0,
    tempFilePaths: [],
    imgs: [],
    tempVideo:[],
    soundState: 0,
    countDownNum:59,
  },
  //监听页面初次载入完成
  onLoad: function (options) {
    var param;
    app.getParam(options, (rel) => {
      param = rel;
    })
    //已ID获取产品
    if (!app.util().isNull(param.id)) {
      this.setData({
        product_id: param.id
      });
    }
    //已扫描获取产品
    if (!app.util().isNull(param.code)) {
      this.setData({
        product_code: param.code
      });
    }
  },
  //每次页面都显示
  onShow:function () {
    app.isLogin((rel) =>{
      this.getAddress();
      this.getProduct();
    })
  },
  //获取API
  getProduct: function () {
    if (this.data.product_id != this.data.order_product_id){
      var parms = {
        product_id: this.data.product_id,
        product_code: this.data.product_code,
      }
      app.api().Get('api/v1/bestbao/product/getView', parms, (result) => {
        if (result.code == 200) {
          this.setData({
            order_product_id: result.data.id,
            order_product: result.data
          })
        }
      })
    }
  },
  /**
     * 提交绑定
     */
  formSubmit: function (e) {
    var data = e.detail.value;
    if (app.util().isNull(data.product_title)) {
      app.wxAlert('产品名称必须填写')
    } else if (app.util().isNull(data.question)) {
      app.wxAlert('故障描述必须填写')
    } else if (app.util().isNull(this.data.address)) {
      app.wxAlert('你的地址必须填写')
    } else {
      wx.showLoading({ title: '提交中', mask: true })
      this.setData({
        disabled:true
      })
      var filePaths, videoPaths, soundPaths
      var is_post = false;
      //上传图片
      this.postFile((file) => { 
        if (file.isend == true){
          filePaths = JSON.stringify(file.filePaths);
          this.postVideo((video) => {//上传视频
            console.log(video);
            if (video.isend == true) {
              videoPaths = JSON.stringify(video.filePaths);
              this.postSound((sound) => {//上传录音
                if (sound.isend == true) {
                  soundPaths = JSON.stringify(sound.filePaths);
                  var parms = {
                    address: this.data.address.id,
                    order_product_id: this.data.order_product_id,
                    urgent: this.data.level,
                    title: data.product_title,
                    question: data.question,
                    imgs: filePaths,
                    video: videoPaths,
                    sound: soundPaths,
                  }
                  app.api().Post('api/v1/bestbao/order/add', parms, (res) => {
                    wx.switchTab({
                      url: '../order',
                    })
                  })
                }
              })
            }      
          })
        }
      })      
    }
  },
/**
  * 读取微信地址
  */
  getAddress: function () {
    let that = this;
    app.api().Get("openapi/v1/user/getaddress", { 'signkey': 'dopay' }, function (rel) {
      if (rel.code == 200) {
        that.setData({
          address: rel.data,
          address_isnull: Object.keys(rel.data).length,
        })
      }
    })
  },
  /**
   * 读取微信地址
   */
  address: function () {
    let that = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.address'] == false) {
          wx.openSetting({
            success: (res) => {
              res.authSetting = {
                "scope.address": true,
              }
            }
          })
        } else {
          wx.chooseAddress({
            success: function (res) {
              var name = res.userName;
              var telNumber = res.telNumber;
              var city = res.provinceName + res.cityName + res.countyName;
              var address = res.detailInfo;
              app.api().Post("openapi/v1/user/createaddress", {
                name: name,
                telphone: telNumber,
                city: city,
                address: address
              }, function (rel) {
                that.setData({
                  address: rel.data,
                  address_isnull: Object.keys(rel.data).length,
                })
              });
            }
          })
        }
      }
    })
  },
  //选择产品
  selectproduct: function () {
    wx.navigateTo({
      url: 'select?focus=input',
    })
  },
  //打开或关闭选择紧急程度
  onSheet: function () {
    this.setData({
      sheet: !this.data.sheet,
    });
  },
  //紧急程度选择
  onSelect: function (e) {
    this.setData({
      sheet: !this.data.sheet,
      level: e.detail.level,
      urgent: e.detail.name
    });
  },
  //图片上传
  postFile: function (callback) {
   // var files = new Array(); 
    upload.Upfiles('api/v1/bestbao/order/upimg', this.data.tempFilePaths, callback);
  },
  selectImg: function () {
    var img = this.data.tempFilePaths;
    if (img.length >= 4) {
      wx.showModal({
        showCancel: false,
        content: '最多上传4张图片'
      })
    } else {
      var count = 4-img.length;
      wx.chooseImage({
        count: count,sizeType: ['compressed'],
        success: (res) => {
          var src = res.tempFilePaths;
          var serlen = src.length;
          for (var i = 0; i < serlen; i++) {
            img.push(src[i]);
          }
          this.setData({
            tempFilePaths: img,
          })
          this.getWidghHeight();
        }
      })
    }
  },
  /**
   * 删除图片
   */
  delImg: function (res) {
    let that = this;
    var array = this.data.tempFilePaths;
    var index = res.target.id;
    if (index > -1) {
      array.splice(index, 1);
    }
    that.setData({
      tempFilePaths: array
    })
  },
  /**
  * 获取图片宽高
  */
  getWidghHeight: function () {
    let that = this;
    const query = wx.createSelectorQuery()
    query.select('.select_img').boundingClientRect(function (res) {
      that.setData({
        width: parseInt(res.width)
      })
    }).exec();
  },
  //拍摄短视频并删除视频
  postVideo: function (callback) {
    upload.Upfiles('api/v1/bestbao/order/upimg', this.data.tempVideo, callback);
  },
  chooseVideo: function () {
    var tempVideo = this.data.tempVideo;
    if (app.util().count(tempVideo) == 1){
      app.wxAlert('仅允许拍摄一个视频');
      return false;
    }
    wx.chooseVideo({
      sourceType: ['camera'],
      maxDuration: 30,
      success:(res) => {
        if (res.duration  > 30){
          app.wxAlert('拍摄失败,禁止大于30秒')
        }else{
          tempVideo.push(res.tempFilePath);
          this.setData({
            tempVideo: tempVideo
          })
        }
      },
      fail: (res) => {
        app.wxAlert('视频录制失败')
      },
    })
  },
  delVideo:function (e) {
    this.setData({
      tempVideo: []
    })
  },
  //当前录音状态
  postSound: function (callback) {
    var tempSound = new Array(); 
    if (!app.util().isNull(this.tempSoundPath)){
      tempSound.push(this.tempSoundPath);
      console.log(tempSound);
      upload.Upfiles('api/v1/bestbao/order/upimg',tempSound,callback);
    }else{
      typeof callback == "function" && callback({
        isend:true,
        filePaths: tempSound
      })
    }
  },
  getSound:function(){
    let soundState = this.data.soundState;
    switch (soundState) {
      case 1: //暂定录音
        this.setData({
          soundState: 2,
          disabled:false
        })
        this.stop();
        break;
      case 2: //录音完成播放或重新录音
        wx.showModal({
          content: '已录制完成.收听还是重新录音',
          cancelText:'重录',confirmText:'播放',
          success:(res)=>{
            if (res.confirm) {
              this.setData({
                soundState: 3
              })
              this.play();
            } else if (res.cancel) {
              this.setData({
                soundState: 1,
                disabled: true
              })
              this.start();
            }
          }
        })
        break;
      case 3: //暂定播放
        this.setData({
          soundState: 2
        })
        this.stopPlay();
        break;
      default: //重新开始
        this.setData({
          soundState: 1,
          disabled:true
        })
        this.start();
    }
  },
  //开始录音的时候
  start: function () {
    recorderManager.start({ duration: 65000, sampleRate: 12000});
    recorderManager.onStart(() => {
      var countDownNum = 59;
      clearInterval(this.times);
      this.times = setInterval(() => {
        this.setData({
          countDownNum: countDownNum--
        })
        if (countDownNum <= 0) {
          clearInterval(this.times);
          this.setData({
            soundState: 2
          })
        }
      },1000);
    });
    //错误回调
    recorderManager.onError((res) => {
      app.wxAlert('录音错误,可能暂时无法录音');
    })
  },
  //停止录音
  stop: function () {
    recorderManager.stop();
    recorderManager.onStop((res) => {
      clearInterval(this.times);
      this.setData({
        countDownNum:59
      })
      this.tempSoundPath = res.tempFilePath;
      const { tempSoundPath } = res
    })
  },
  //暂定播放
  stopPlay: function () {
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.tempSoundPath,
    innerAudioContext.stop(() => {
      console.log('暂定播放')
    })
  },
  //播放声音
  play: function () {
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.tempSoundPath,
    innerAudioContext.play()
    innerAudioContext.onEnded((res) => {
      this.setData({
        soundState:2
      })
      this.stopPlay();
    })
    innerAudioContext.onError((res) => {
      app.wxAlert('播放失败,请重新录音');
    })
  },
})